package com.syc.test;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @Description:
 * @Author: 黄浩键
 * @CreateDate: 2025-04-12
 * @Version: 1.0.0
 * @Company: 深圳中泓在线股份有限公司
 * @menu
 */
public class WordTest02 {


    public static void main(String[] args) throws Exception {
        // 创建一个新的 Word 文档
        XWPFDocument document = new XWPFDocument();

        // 插入目录
        insertTOC(document);

        // 添加内容
        addStyledParagraph(document, "Heading 1", "第一章：介绍");
        addNormalParagraph(document, "这是第一章的内容。");

        addStyledParagraph(document, "Heading 1", "第二章：方法");
        addStyledParagraph(document, "Heading 2", "2.1 方法一");
        addNormalParagraph(document, "这是方法一的详细描述。");

        addStyledParagraph(document, "Heading 2", "2.2 方法二");
        addNormalParagraph(document, "这是方法二的详细描述。");

        addStyledParagraph(document, "Heading 1", "第三章：结论");
        addNormalParagraph(document, "这是结论部分的内容。");

        // 保存文档
        try (FileOutputStream out = new FileOutputStream("E:\\temps\\广交会需求\\example_with_toc.docx")) {
            document.write(out);
        }
    }

    private static void addStyledParagraph(XWPFDocument document, String style, String text) {
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setStyle(style); // 设置样式
        XWPFRun run = paragraph.createRun();
        run.setText(text);
    }

    private static void addNormalParagraph(XWPFDocument document, String text) {
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);
    }

    private static void insertTOC(XWPFDocument document) {
        XWPFParagraph tocParagraph = document.createParagraph();
        // 插入 TOC 字段代码
        tocParagraph.getCTP().addNewFldSimple()
                .setInstr("TOC \\o \"1-3\" \\h \\z \\u"); // 生成目录的字段代码
    }


}
